package com.gitee.chili.leisure.config;

import com.gitee.chili.leisure.constant.Constant;
import com.gitee.chili.leisure.properties.FilterProperties;
import com.gitee.chili.leisure.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties.ZuulRoute;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

@Primary
@Configuration
@EnableSwagger2
public class DocumentationConfig implements SwaggerResourcesProvider {

    @Autowired
    private ZuulProperties properties;
    @Autowired
    private FilterProperties filterProperties;

    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resources = new ArrayList<>();
        Stream<ZuulRoute> zuulRouteStream = properties.getRoutes().values().stream();
        zuulRouteStream.forEach(route -> {
            String location = Utils.connect(Constant.rootPath, route.getServiceId(), filterProperties.getLocation());
            resources.add(swaggerResource(route.getServiceId(), location, filterProperties.getVersion()));
        });
        return resources;

    }

    private SwaggerResource swaggerResource(String name, String location, String version) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion(version);
        return swaggerResource;
    }

}